package com.prelearning.at_springboot.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.prelearning.at_springboot.constant.WorkWXAPI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 *  企业微信接口处理器
 * </p>
 *
 * @author cgr
 * @since 2022-04-28
 */

@Component
public class WorkWXAPIUtil {

    //配置为全局变量
    @Value("${key.access_token}")
    private static String accessToken =getAccessToken();

//    public static void main(String[] args) {
////        System.out.println("{\"attrs\":[]}".substring(9,"{\"attrs\":[]}".length()-1));
////        String[] r="[0,0]".substring(1,4).split(",");
////        r[0]=String.valueOf(Integer.parseInt(r[0])+1);
////        System.out.println(Arrays.toString(r));
//
////        System.out.println(LocalDateTime.now());
////
////        LocalDateTime startTime=LocalDateTime.of(2022, 5, 7, 16, 40, 38);
////        LocalDateTime nowTime=LocalDateTime.now();
////        System.out.println(Duration.between( startTime, nowTime).toMillis()>0);
//
//        postMessage("group4");
//
//    }

    //获取access_token
    public static String getAccessToken() {
        return getHttp(WorkWXAPI.getGetAccessTokenUrl()).get("access_token").toString();
    }

    //获取{username,school_number}
    public static String[] getUserInfo(String userid) {
        String extattr = getHttp(String.format(WorkWXAPI.GET_USER_DETAIL,accessToken,userid)).get("extattr").toString();

        if(!extattr.substring(10, extattr.length() - 2).equals("")){
            JSONArray jsonArray = JSONArray.parseArray(extattr.substring(9,extattr.length()-1));///
            JSONObject object =JSONArray.parseObject(jsonArray.get(0).toString());

//            System.out.println("* user_number : " + object.getString("value"));
            return new String[]{getHttp(String.format(WorkWXAPI.GET_USER_DETAIL, accessToken, userid)).get("name").toString(), object.getString("value")};
        }else{
            return new String[]{getHttp(String.format(WorkWXAPI.GET_USER_DETAIL, accessToken, userid)).get("name").toString(), ""};
        }

    }

    //根据群id获取群组成员
    public static String[] getGroupMember(String groupid) {
        String chat_info = getHttp(String.format(WorkWXAPI.GET_CHAT,accessToken,groupid)).get("chat_info").toString();

        Map map = null;
        if (!Objects.equals(chat_info, "")) {
            map = (Map) JSON.parse(chat_info); //阿里巴巴fastjson

            assert map != null;
            String member= map.get("userlist").toString();
//            System.out.println("* userlist : " + member);

            return member.substring(1, member.length() - 1).replaceAll("\"", "").split(",");

        }else{
            return null;
        }
    }

    //根据群id获取result列表
    public static JSONObject getResult(String groupid){
        String[] members =getGroupMember(groupid);
        assert members != null;
        JSONObject result =new JSONObject();
        JSONArray jsonArray=new JSONArray();

        for(String userid:members){
            JSONObject jsonObject =new JSONObject();
            String[] userInfo=getUserInfo(userid);

            jsonObject.put("user_id",userid);
            jsonObject.put("user_name",userInfo[0]);
            jsonObject.put("school_number",userInfo[1]);
            jsonObject.put("sign_in_status",0);
            jsonObject.put("sign_in_time","");

            jsonArray.add(jsonObject);
        }
        result.put("result",jsonArray);

//        System.out.println("*result"+result.getString("result"));
        return result;
    }



    //http get请求，获取取key的数据
    public static Map getHttp(String url) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(headers);

        String response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();

        Map map = null;
        if (!Objects.equals(response, "")) {
//            System.out.println("* response : " + response);
            map = (Map) JSON.parse(response); //阿里巴巴fastjson

            assert map != null;
            if ( Integer.parseInt(map.get("errcode").toString())==0) {
                return map;
            }
        }else{
            return null;
//            return "! response empty !";
        }
        return null;
//        return "! error code : "+map.get("errcode").toString();
    }

    //http post请求，向服务端发送数据
    public static Map postMessage(String chatId) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        String url = String.format(WorkWXAPI.MESSAGE_CHAT,accessToken);
        JSONObject request =new JSONObject();
        JSONObject jsonObject =new JSONObject();
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        jsonObject.put("title","签到通知");
        jsonObject.put("description","<div class=\"gray\">"+formatter.format(date)+"</div> <div class=\"highlight\">限时签到已经开始，请同学们及时完成！</div>");
        jsonObject.put("url","http://localhost:8080/");
        jsonObject.put("btntxt","立即查看");
        //入参
        request.put("chatid",chatId);
        request.put("msgtype", "textcard");
        request.put("textcard", jsonObject);
        request.put("safe", 0);
        //请求
        String result = restTemplate.postForObject(url,request,String.class);
        System.out.println(result);

        return null;

//        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
//        System.out.println("responseEntity.getBody() = " + responseEntity.getBody());

    }

}
